import React from 'react'
import { Toast, List, InputItem, WhiteSpace, Picker, DatePicker, TextareaItem, Switch, Button } from 'antd-mobile'
import { createForm } from 'rc-form'

import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import {actions} from '../../reducers'
import {actions as CategoryAction} from '../../reducers/category'
import {actions as ProjectAction} from '../../reducers/project'

import CustomImagePicker from '../../components/image-picker'
import moment from 'moment'
import utils from '../../common/utils'
import execute from '../my_project/execute';

const is_ok = (v) => 
   Array.isArray(v) && v[0]

class NewProject extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      hasError: false,
      files: [],
      parent_id: 0,
      project_id: 0,
      category_id: -1,
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.project.id&&this.props.project.id!=nextProps.project.id) {
      this.setFieldsValue(this.props.project)
    }
  }

  componentDidMount() {
    let parent_id = utils.getQueryString('parent_id'),
      project_id = this.props.match.params.project_id
    this.setState({parent_id, project_id})
    this.props.get_categories()
    this.props.get_user_parent_projects()
    project_id&&this.props.get_project_detail(project_id, 'publish')
    
    if (project_id && this.props.project.id) {
      this.setState({category_id: this.props.project.category_id}, ()=>this.setFieldsValue(this.props.project))
    }
  }

  formatPickerData(arrs, label='name', value='id') {
    let data = []
    arrs.map(x=>data.push({label: x[label], value: Number(x[value])}))
    return data
  }
  // 保存 或 发布 项目
  submit = (mold) => {
    this.props.form.validateFields((errors, value) => {
        let imgs = this.state.files.map(x => x.uri)
        value.resource = imgs
        
        console.log(errors,value, mold)
        // 草稿 && 填写了title
        if (mold=='draft' && value.title) {
          value.assign_type = value.assign_type ? 'system' : 'custom'
          value.expect_at = moment(value.expect_at).format('YYYY-MM-DD')
          value.category_id = is_ok(value.category_id) ? Number(value.category_id[0]) : 0
          value.parent_id = is_ok(value.parent_id) ? value.parent_id[0] : 0
          value.content = value.content || ''
          this.props.save_project(value, mold, this.state.project_id)
          return
        } 
        // 草稿 && 没有填写title
        if (mold=='draft' && !value.title) {
          Toast.info('请填写项目名称')
          return
        }

        // 发布项目
        if (mold=='publish' && errors) {
          this.setState({hasError: true})
        } else {
          value.assign_type = value.assign_type ? 'system' : 'custom'
          value.expect_at = moment(value.expect_at).format('YYYY-MM-DD')
          value.category_id = Number(value.category_id[0])
          value.parent_id = is_ok(value.parent_id) ? value.parent_id[0] : 0
          this.props.save_project(value, mold, this.state.project_id)
        }
    });
  }

  setFieldsValue = (project) => {
    console.log(project, new Date(expect_at))
    let {title, category_id, category_name, expect_at, assign_type, parent_id, content} = project
    this.props.form.setFieldsValue({
      title,
      category_id: [Number(category_id)],
      category_name: category_name==null?'':category_name,
      expect_at: new Date(expect_at),
      parent_id,
      content,
      assign_type: Boolean(assign_type=='system')
    })
    this.setState({files: utils.formatResource(project.project_resource)})
  }

  render() {
      const { getFieldProps, getFieldError } = this.props.form,
        categories = this.formatPickerData(this.props.categories),
        parents = this.formatPickerData(this.props.user_parent_projects, 'title'),
        {files, hasError} = this.state
      
        categories.push({label: '自定义', value: 0})

      return (
      <div className='form-div'>
          <WhiteSpace/>
          <List>
            <InputItem
              {...getFieldProps('title',
                {rules: [{required: true, message: '项目名称必须填写'}]}
              )
              }
              clear
              ref={el => this.autoFocusInst = el}
            >项目名称</InputItem>
            {getFieldError('title')&&hasError?<div className='err-msg'>{getFieldError('title')}</div>: null }
          </List>
          <WhiteSpace/>

          <List>  
            <Picker 
            data={categories}   
            cols={1} 
            {...getFieldProps('category_id',
              {rules: [{required: true, message: '请选择'}]}
            )} 
            onOk={v => this.setState({category_id: v[0]})}
            >
                <List.Item arrow="horizontal">项目类别</List.Item>
            </Picker>
            {getFieldError('category_id')&&hasError?<div className='err-msg'>{getFieldError('category_id')}</div>: null }              
          </List>
          <WhiteSpace/>

          <CustomCategory 
            category_id={this.state.category_id}
            getFieldProps={getFieldProps}
            getFieldError={getFieldError}
            hasError={hasError}
          />
          
          <List>  
            <DatePicker
            {...getFieldProps('expect_at',
              {rules: [{required: true, message: '请选择'}]}
            )}
              minDate={new Date()}
              mode="date"
              extra="请选择"
            >
              <List.Item arrow="horizontal">项目截止时间</List.Item>
            </DatePicker>
            {getFieldError('expect_at')&&hasError?<div className='err-msg'>{getFieldError('expect_at')}</div>: null }                            
          </List>
          <WhiteSpace/>

          {
            !this.props.user.is_manager ? null :
              <React.Fragment>
                <List>  
                  <Picker 
                  disabled={Boolean(this.state.parent_id)}
                  data={parents} 
                  cols={1} 
                  {...getFieldProps('parent_id', {
                    initialValue: [Number(this.state.parent_id)]
                  })} 
                  >
                      <List.Item arrow="horizontal">上级项目</List.Item>
                  </Picker>
                  {getFieldError('parent_id')&&hasError?<div className='err-msg'>{getFieldError('parent_id')}</div>: null }              
                </List>
                <WhiteSpace/>
              </React.Fragment>
          }

          <List> 
            <TextareaItem
              {...getFieldProps('content',
                {rules: [{required: true, message: '必须填写'}]}
              )}
              title="需求说明"
              rows={8}
              count={500}
            />
            {getFieldError('content')&&hasError?<div className='err-msg'>{getFieldError('content')}</div>: null }              
          </List>
          <WhiteSpace/>

          <List >    
          
            <CustomImagePicker 
                files={files} 
                callback={(files, type, index) => this.setState({files})}
            />
            
          </List>
          <WhiteSpace/>

          {/* <div style={{position: 'absolute', bottom: '80px', left: '15px', 'right': '15px'}}> */}
          <List> 
            <List.Item
              extra={
              <Switch
                color="#0ea2ec"
                {...getFieldProps('assign_type', {
                  initialValue: true,
                  valuePropName: 'checked',
                })}
                onClick={(checked) => { console.log(checked); }}
              />}
            >由系统自动分配
            </List.Item>
          </List>
          
          {/* </div> */}
          <div className="btns-nofixed">
            <a className="release" onClick={()=>this.submit('draft')}>保存</a>
            <a className="contact" onClick={()=>this.submit('publish')}>保存并发布</a>
          </div>
      </div>
      
      )
  }
}
{/* 项目类别为自定义时显示 */}
const CustomCategory = ({category_id, getFieldProps, getFieldError, hasError}) => {
  if (category_id==0) {
    return <React.Fragment>
    <List>
      <InputItem
        {...getFieldProps('category_name',
          {rules: [{required: true, message: '项目类别必须填写'}]}
        )
        }
        clear
      >自定义类别</InputItem>
      {getFieldError('category_name')&&hasError?<div className='err-msg'>{getFieldError('category_name')}</div>: null }
    </List>
    <WhiteSpace/>
    </React.Fragment>
  }
  return null
}

function mapStateToProps(state) {
  return {
    categories: state.category.list,
    user_parent_projects: state.project.user_parent_projects,
    project: state.project.detail,
    user: state.user.userInfo,
  }
}

function mapDispatchToProps(dispatch) {
  return  {
    get_categories: bindActionCreators(CategoryAction.get_cat_list, dispatch),
    save_project: bindActionCreators(ProjectAction.save_project, dispatch),
    get_user_parent_projects: bindActionCreators(ProjectAction.get_user_parent_projects, dispatch),
    get_project_detail: bindActionCreators(ProjectAction.get_detail, dispatch),
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(createForm()(NewProject))